package cc.atliberty.oa.controller;

import cc.atliberty.oa.pojo.EmployeeVo;
import cc.atliberty.oa.service.EmployeeService;
import cc.atliberty.oa.utils.ResultObj;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@WebServlet("/employee/addEmployee")
public class AddEmployeeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        String identity = request.getParameter("identity");
        String empname = request.getParameter("empname");

        Integer sex = null;
        if (request.getParameter("sex") != null){
            sex = Integer.valueOf( request.getParameter("sex"));
        }
        String address = request.getParameter("address");
        String phone = request.getParameter("phone");
        String dept = request.getParameter("dept");
        Integer page = null;
        if (request.getParameter("page") != null){
            page = Integer.valueOf(request.getParameter("page"));
        }
        Integer limit = null;
        if (request.getParameter("limit") != null){
            limit = Integer.valueOf(request.getParameter("limit"));
        }
        String[] ids = request.getParameterValues("ids");
        EmployeeVo employeeVo = new EmployeeVo(identity, empname, sex, address, phone, dept, new Date(), page, limit, ids);
        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        EmployeeService employeeService = context.getBean("EmployeeService", EmployeeService.class);
        ObjectMapper mapper = new ObjectMapper();
        String jsonStr = null;
        try {
            employeeService.addEmployee(employeeVo);
            jsonStr = mapper.writeValueAsString(ResultObj.ADD_SUCCESS);
        } catch (Exception e){
            jsonStr = mapper.writeValueAsString(ResultObj.ADD_ERROR);
        }
        response.getWriter().print(jsonStr);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
